<template>
  <!--  转换类型  -->
  <div class="main-wk">
    <el-form ref="ruleForm" :model="formData" class="demo-ruleForm" @submit.native.prevent>
      <div v-for="(item, index) in formData.list">
        <el-row class="row" :gutter="20" style="padding: 10px 0">
          <el-col :span="2">第{{ index + 1 }}步</el-col>
          <el-col :span="6">
            <el-form-item
              :prop="`list.${index}.firstValue`"
              :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
            >
              <el-select
                v-model="item.firstValue"
                filterable
                placeholder="请选择"
                style="width: 100%"
                @change="handleFirst($event, index)"
              >
                <el-option
                  v-for="(i, childIndex) in firstList"
                  :key="childIndex"
                  :label="i.ruleName"
                  :value="i.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--    二级框      -->
          <el-col v-if="formData.list[index].level == 2" :span="6">
            <el-form-item
              :prop="`list.${index}.desc`"
              :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
            >
              <el-input
                v-model="item.desc"
                type="textarea"
                :row="1"
                style="width: 100%"
                @blur="getInptValue($event, index)"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="formData.list[index].level == '1'" :span="6">
            <el-form-item
              :prop="`list.${index}.secondValue`"
              :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
            >
              <el-select
                v-model="item.secondValue"
                filterable
                placeholder="请选择"
                style="width: 100%"
                @change="handleSecond($event, index)"
              >
                <el-option
                  v-for="(item, childIndex) in secondList[index].list"
                  :key="childIndex"
                  :label="item.ruleName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--    下拉树      -->
          <el-col v-if="formData.list[index].level == '3'" :span="6">
            <selectTree
              :form-data="treeFormData"
              :selected-value="item.secondValue"
              style="width: 100%"
              @handleNodeClick="(data) => handleNodeClick(data, index)"
            />
          </el-col>
          <!--    二级框 结束      -->

          <!--    三级框      -->
          <el-col v-if="formData.list[index].thirdLevel == '2'" :span="6">
            <el-form-item
              :prop="`list.${index}.thirdDesc`"
              :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
            >
              <el-input
                v-model="item.thirdDesc"
                style="width: 100%"
                type="textarea"
                :row="1"
                @input="getInptValue($event, index)"
              />
            </el-form-item>
          </el-col>
          <el-col
            v-if="
              (formData.list[index].level == '1' && formData.list[index].thirdLevel == '1') ||
                formData.list[index].thirdLevel == '3'
            "
            :span="6"
          >
            <el-form-item
              :prop="`list.${index}.thirdValue`"
              :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
            >
              <el-select v-model="item.thirdValue" style="width: 100%" filterable placeholder="请选择" @change="handleThird(item.thirdValue,index)">
                <el-option
                  v-for="(item, childIndex) in thirdList[index].list"
                  :key="childIndex"
                  :label="item.ruleName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--    三级框 结束      -->

          <!--    操作按钮       -->
          <el-col :span="2">
            <el-button @click="handleCheck(index)">校验</el-button>
          </el-col>
          <el-col v-if="formData.list.length > 1" :span="2">
            <el-button type="text" @click="handleDel(index)">删除</el-button>
          </el-col>
          <el-col v-if="formData.list[index].show" :span="24">
            <span class="message-box success">{{ formData.list[index].message }}</span>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <el-button class="row-btn" type="primary" @click="handleAdd()">新增一行</el-button>
  </div>
</template>

<script>
import { getRuleTrans, getRuleDictList, convertRuleCheck } from '@/api/milkyway/accessRules'
import selectTree from '@/components/Common/selectTree'
import { deepClone } from '@/utils/index'

export default {
  name: 'ConvertType',
  components: { selectTree },
  props: {
    productCode: {
      type: String,
      default() {
        return '' // 1014934097640042496
      }
    },
    paramValue: {
      type: String,
      default() {
        return ''
      }
    },
    echoData: {
      type: Object,
      default() {
        return {}
      }
    },
    echoRuleMethodList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      // level第二个框的类型:1 下拉框  2文本框  3 为特殊处理字典转换  4  无参数 5 为特殊处理数据描述
      isTreeSelect: false,
      formData: {
        list: [{ firstValue: '', message: '', show: false, level: 4, thirdLevel: 4 }]
      },
      // 提交的数据
      ruleMethodList: [
        {
          paramValue: '',
          ruleGroup: '',
          ruleMethod: ''
        }
      ],
      show: false,
      firstList: [],
      secondList: [{ list: [] }],
      thirdList: [{ list: [] }],
      // 非自定义下拉框用到的id值
      parentId: 0,

      /*      level: [],
            // 第三个框的类型:1 下拉框  2文本框  3 为特殊处理字典转换  4  无参数 5 为特殊处理数据描述
            thirdLevel: [],*/
      treeFormData: [],
      isCheck: false
    }
  },
  watch: {
    echoData: {
      handler(newVal) {
        if (newVal?.convertTypeEchoData?.list && newVal?.convertTypeEchoData?.list.length > 0) {
          this.formData.list = deepClone(newVal.convertTypeEchoData.list)
          // 获取第二个框的数据
          this.formData.list.forEach((item, index) => {
            if (!this.secondList[index]) {
              this.secondList[index] = { list: [] }
            }
            if (!this.thirdList[index]) {
              this.thirdList[index] = { list: [] }
            }
            if (item.level == '1') {
              getRuleTrans(item.firstValue).then((res) => {
                this.$nextTick(() => {
                  this.secondList[index].list = res
                  this.$forceUpdate()
                })
              })
            }
            if (this.formData.list[index].thirdLevel == '1') {
              getRuleTrans(item.secondValue).then((res) => {
                this.thirdList[index].list = res
              })
            }
          })
        } else {
          this.formData.list = [
            {
              firstValue: '',
              message: '',
              show: false,
              level: 4,
              thirdLevel: 4
            }
          ]
        }
      },
      immediate: true,
      deep: true
    },
    echoRuleMethodList: {
      handler(newVal) {
        if (newVal) {
          this.ruleMethodList = deepClone(newVal)
          if (this.ruleMethodList.length == 0) {
            this.ruleMethodList = [
              {
                paramValue: '',
                ruleGroup: '',
                ruleMethod: ''
              }
            ]
          }
        }
      },
      immediate: true,
      deep: true
    },
    paramValue: {
      handler(newVal) {
        if (newVal && this.ruleMethodList[0]?.paramValue) {
          const firstParamValue = JSON.parse(this.ruleMethodList[0].paramValue)
          firstParamValue[0] = newVal
          this.ruleMethodList[0].paramValue = JSON.stringify(firstParamValue)
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.getFirstList()
    getRuleDictList(this.productCode).then((res) => {
      this.treeFormData = res
    })
  },
  methods: {
    // 获取第一列的下拉框数据
    getFirstList() {
      getRuleTrans(this.parentId).then((res) => {
        this.firstList = res
      })
    },
    // 点击第一个框数据
    handleFirst(value, index) {
      this.formData.list[index].thirdLevel = '4'
      if (this.formData.list[index].secondValue) {
        this.formData.list[index].secondValue = undefined
      }
      const currentData = this.firstList.filter((i) => {
        return i.id == value
      })
      this.formData.list[index].level = currentData[0].level
      if (this.formData.list[index].level == '1') {
        getRuleTrans(value).then((res) => {
          this.secondList[index].list = res
          this.$forceUpdate()
        })
      } else if (this.formData.list[index].level == '2') {
        this.ruleMethodList[index].ruleGroup = currentData[0].ruleGroup
        this.ruleMethodList[index].ruleMethod = currentData[0].ruleMethod
      } else if (this.formData.list[index].level == '3') {
        this.ruleMethodList[index].ruleGroup = currentData[0].ruleGroup
        this.ruleMethodList[index].ruleMethod = currentData[0].ruleMethod
        // 获取特殊字典-获取映射字典
        getRuleDictList(this.productCode).then((res) => {
          this.treeFormData = res
        })
        // this.formData.list[index].secondValue = undefined
      }
    },
    // 点击第二个择框
    handleSecond(value, index) {
      this.$nextTick(() => {
        this.$set(this.formData.list[index], 'thirdValue', '')
        if (!this.ruleMethodList[index]) {
          this.ruleMethodList[index] = {
            ruleGroup: '',
            ruleMethod: '',
            paramValue: JSON.stringify('')
          }
        }
        const currentData = this.secondList[index].list.filter((i) => {
          return i.id == value
        })

        this.formData.list[index].thirdLevel = currentData[0].level
        switch (this.formData.list[index].thirdLevel) {
          case 1:
            getRuleTrans(value).then((res) => {
              this.thirdList[index].list = res
              this.ruleMethodList[index].paramValue = JSON.stringify([this.paramValue])
              this.ruleMethodList[index].ruleGroup = res[0].ruleGroup
              this.ruleMethodList[index].ruleMethod = res[0].ruleMethod
              this.$forceUpdate()
            })
            break
          case 2:
            // this.ruleMethodList[index].paramValue=JSON.stringify(THIS)
            this.ruleMethodList[index].ruleGroup = currentData[0].ruleGroup
            this.ruleMethodList[index].ruleMethod = currentData[0].ruleMethod
            break
          case 3:
            this.ruleMethodList[index].ruleGroup = currentData[0].ruleGroup
            this.ruleMethodList[index].ruleMethod = currentData[0].ruleMethod
            // 获取特殊字典-获取映射字典
            getRuleDictList(this.productCode).then((res) => {
              this.treeFormData = res
            })
            break
          case 4:
            this.ruleMethodList[index].ruleGroup = currentData[0].ruleGroup
            this.ruleMethodList[index].ruleMethod = currentData[0].ruleMethod
            if (this.formData.list[index].level == '3') {
              this.ruleMethodList[index].paramValue = JSON.stringify([this.paramValue, value])
            } else {
              this.ruleMethodList[index].paramValue = JSON.stringify([this.paramValue])
            }

            break
        }
        this.$forceUpdate()
      })
    },
    /** 获取二级文本的值*/
    getInptValue(value, index) {
      this.ruleMethodList[index].paramValue = JSON.stringify([this.paramValue, value])
    },
    // 点击第三个框
    handleThird(val, index) {
      // console.log(this.formData.list[index])
      const selectList = this.thirdList[index].list.filter(i => {
        return i.id === val
      })
      this.ruleMethodList[index].ruleMethod = selectList[0].ruleMethod
    },
    // 新增一行
    handleAdd() {
      const index = this.formData.list.length - 1
      if (this.formData.list[index].show) {
        this.formData.list.push({ firstValue: '', message: '', show: false })
        this.ruleMethodList.push({
          ruleGroup: '',
          ruleMethod: '',
          paramValue: JSON.stringify('')
        })
        this.secondList.push({ list: [] })
        this.thirdList.push({ list: [] })
      } else {
        this.$message.error('请校验最后一步再进行新增')
      }
    },
    /** 删除某一行*/
    handleDel(index) {
      this.formData.list.splice(index, 1)
      this.ruleMethodList.splice(index, 1)
    },
    /**  下拉树点击事件 */
    handleNodeClick(value, index) {
      this.formData.list[index].secondValue = value
      this.ruleMethodList[index].paramValue = JSON.stringify([this.paramValue, value])
    },
    /** 校验 */
    handleCheck(index) {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (!this.ruleMethodList[index]) {
            this.ruleMethodList[index] = {
              ruleGroup: '',
              ruleMethod: '',
              paramValue: JSON.stringify('')
            }
          }
          let newParamValue = []
          if (index == 0) {
            if (this.formData.list[index].thirdLevel == 4 || this.formData.list[index].thirdLevel == 1) {
              newParamValue = this.ruleMethodList[index].paramValue + ''
            } else if (this.formData.list[index].thirdLevel == 2 || this.formData.list[index].level == 3) {
              newParamValue = JSON.stringify([this.paramValue, this.formData.list[index].thirdDesc])
            }
          } else {
            newParamValue =
              this.formData.list[index].thirdLevel == 2 || this.formData.list[index].level == 3
                ? JSON.stringify([
                  this.formData.list[index - 1].message,
                  JSON.parse(this.ruleMethodList[index].paramValue)[1]
                ])
                : JSON.stringify([this.formData.list[index - 1].message + ''])
          }
          const newRuleMethodList = {
            // paramValue: index == 0 ? this.ruleMethodList[index].paramValue+'' :this.formData.list[index].thirdLevel==2 || this.formData.list[index].level==3?JSON.stringify([this.formData.list[index - 1].message,JSON.parse(this.ruleMethodList[index].paramValue)[1]]):JSON.stringify([this.formData.list[index - 1].message+'']),
            paramValue: newParamValue,
            ruleGroup: this.ruleMethodList[index].ruleGroup,
            ruleMethod: this.ruleMethodList[index].ruleMethod
          }
          convertRuleCheck(newRuleMethodList).then((res) => {
            this.formData.list[index].show = true
            this.formData.list[index].message = res
            if (index !== this.formData.list.length - 1) {
              this.formData.list.forEach((i, indx) => {
                if (indx > index) {
                  this.formData.list[indx].show = false
                  this.formData.list[indx].message = ''
                }
              })
            }
          })
        }
      })
    },
    /** 校验必填项*/
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            const isAllValidate = this.formData.list.every(i => {
              return i.show
            })
            if (isAllValidate) {
              resolve({
                formData: this.formData,
                ruleMethodList: this.ruleMethodList
              })
            } else {
              this.$message.error('请完成校验')
              return false
            }

            return true
          } else {
            this.$message.error('请完善表单')
            return false
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-wk {
  width: 100%;
  padding: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;

  .row {
    border-bottom: 1px solid #e8e8e8;
  }

  .row-btn {
    width: 100%;
  }
}

.message-box {
  display: inline-block;
  width: 100%;
  min-height: 36px;
  margin: 10px auto 0;
  padding: 0 10px;
  border-radius: 4px;

  &.success {
    background-color: #e7faf0;
    border-color: #d0f5e0;
    color: #13ce66;
  }

  &.error {
    background: rgba(255, 53, 53, 0.2);
    color: #fa541c;
    border: 1px solid #ffa39e;
  }
}

::v-deep .el-textarea__inner {
  height: 36px !important;
  line-height: 24px !important;
  min-height: 36px !important;
}
</style>
